package com.test.rxjavademo;

import android.util.Log;

import java.util.ArrayList;
import java.util.List;

import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;

public class CreateOperatorDemo {

    public static final String TAG = "CreateOperatorDemo";

    Observer<Object> observer = new Observer<Object>() {
        @Override
        public void onSubscribe(Disposable d) {
            //建立订阅后会调用该方法：相当于是订阅前置操作
            Log.e(TAG, "onSubscribe........");
        }

        @Override
        public void onNext(Object o) {
            Log.e(TAG, "onNext......" + o.toString());
        }

        @Override
        public void onError(Throwable e) {
            Log.e(TAG, "onError......." + e.toString());
        }

        @Override
        public void onComplete() {
            Log.e(TAG, "onComplete.......");
        }
    };

    public   void test1(){
        Observable.create(new ObservableOnSubscribe<Object>() {
            @Override  //建立订阅关系
            public void subscribe(ObservableEmitter<Object> emitter) throws Exception {

                //事件产生的地方
                Log.e(TAG, "subscribe: " + "发射1" );
                emitter.onNext("1");
                Log.e(TAG, "subscribe: " + "发射2" );
                emitter.onNext("2");
                Log.e(TAG, "subscribe: " + "发射3" );
                emitter.onNext("3");
                emitter.onComplete();
                Log.e(TAG, "发射完成");
            }
        }).subscribe(new Observer<Object>() {
            @Override
            public void onSubscribe(Disposable d) {
                //建立订阅后会调用该方法：相当于是订阅前置操作
                Log.e(TAG, "onSubscribe........");
            }

            @Override
            public void onNext(Object o) {
                Log.e(TAG, "onNext......" + o.toString());
            }

            @Override
            public void onError(Throwable e) {
                Log.e(TAG, "onError......." + e.toString());
            }

            @Override
            public void onComplete() {
                Log.e(TAG, "onComplete.......");
            }
        });
    }

    public void test2(){
        Observable.just("1","2","3")
                .subscribe(observer);
    }

    public void test3(){
        Observable.fromArray("1","2","3")
                .subscribe(observer);
    }

    public void test4(){
        List<String> list = new ArrayList<>();
        list.add("jjjjj");
        list.add("ddddd");
        list.add("ggggg");
        Observable.fromIterable(list)
                .subscribe(observer);
    }
}
